package com.baomidou.ant.utils;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *@description:   判断Vo对象中的属性是否为空
 *@author:        zhoubeibei
 *@email:         zhoubb@fpe.com.cn
 *@date:          2022/4/7
 *@time:          15:32
 */
public class VoUtilsTool {
    /****
     * @param object 对象
     * @return 如果对象不为空，且没有空值。返回false，对象为空或者有空值，返回true
     * */
    public static boolean checkObjFieldIsNull(Object object){
        boolean flag = false;
        if(null!=object){
            for(Field field : object.getClass().getDeclaredFields()){
                //在用反射时访问私有变量（private修饰变量）
                field.setAccessible(true);
                try {
                    if(field.get(object) == null || field.get(object).equals("")){
                        flag = true;
                        return flag;
                    }
                    if(field.get(object) != null&&field.get(object).toString().trim().equals("")){
                        flag = true;
                        return flag;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }else{
            flag=true;
        }
        return flag;
    }


    /****
     * @param obj 对象
     * @return 如果对象全空。返回false，对象不空，返回true
     * */
    public static boolean isObjectNull(Object obj){
        if (obj != null) {
            Class<?> objClass = obj.getClass();
            Method[] declaredMethods = objClass.getDeclaredMethods();
            if (declaredMethods.length > 0) {
                int methodCount = 0; // get 方法数量
                int nullValueCount = 0; // 结果为空

                for (Method declaredMethod : declaredMethods) {
                    String name = declaredMethod.getName();
                    if (name.startsWith("get") || name.startsWith("is")){
                        methodCount += 1;
                        try {
                            Object invoke = declaredMethod.invoke(obj);
                            if (invoke == null) {
                                nullValueCount += 1;
                            }
                        } catch (IllegalAccessException | InvocationTargetException e){
                            e.printStackTrace();
                        }
                    }
                }
                return methodCount == nullValueCount;
            }
        }
        return false;
    }

}
